package com.redis;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @ClassName: RedisFunction
 * @Description: redis操作类
 * @author baozhijian
 * @date 2017年8月20日 下午8:45:12
 * @version V1.0
 */
public class RedisFunction implements RedisInterface {

	private Jedis jedis = null;

	public RedisFunction(String host, int port) {

		this.jedis = new Jedis(host, port, 100000);
		this.jedis.configSet("timeout", "30");
		this.jedis.connect();
	}

	private boolean CheckConnection() {
		if (this.jedis.ping().equalsIgnoreCase("pong")) {
			return true;
		} else {
			this.jedis.connect();
			if (this.jedis.ping().equalsIgnoreCase("pong")) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean SetKey(String key, String value, int outtime) {
		if (!CheckConnection()) {
			return false;
		}
		if (this.jedis.set(key, value).equalsIgnoreCase("OK")) {
			if (outtime != 0) {
				if (this.jedis.expire(key, outtime) > 0) {
					return true;
				}
			} else {
				return true;
			}
		}
		return false;
	}

	@Override
	public Object GetKey(String key) {
		if (!CheckConnection()) {
			return null;
		}
		return this.jedis.get(key);
	}

	@Override
	public boolean DelKey(String key) {
		if (!CheckConnection()) {
			return false;
		}
		if (this.jedis.del(key) > 0) {
			return true;
		}
		return false;
	}

	public boolean flushall() {
		if (!CheckConnection()) {
			return false;
		}

		if (this.jedis.flushAll().equalsIgnoreCase("OK")) {
			return true;
		}
		return false;
	}

	public boolean WatchAdd(String key, String value, int outtime) {
		if (!CheckConnection()) {
			return false;
		}

		this.jedis.watch(key);
		Transaction transaction = jedis.multi();
		transaction.set(key, value);
		transaction.expire(key, outtime);
		List<Object> list = transaction.exec();
		if (list.get(0).toString().equalsIgnoreCase("OK") && Integer.valueOf(list.get(1).toString()) > 0) {
			return true;
		}
		return false;
	}

}
